<!--
 * @Date: 2021-06-23 13:38:14
 * @LastEditors: Mingdeng
 * @LastEditTime: 2021-06-23 15:12:29
 * @FilePath: /m-uniapp-template/components/m-upload-list/m-upload-list.vue
-->
<template>
  <view class="m-upload-list-c">
    <view class="item" v-for="(urlItem, index) in value" :key="urlItem">
      <m-upload
        :src="urlItem"
        :bgColor="bgColor"
        tips=""
        :size="size"
        @uploaded="handleToggledPic($event, index)"
        @del="handleDelPic(index)"
      >
      </m-upload>
    </view>
    <view class="item" v-if="value.length < count">
      <m-upload
        :bgColor="bgColor"
        :size="size"
        :count="uploadCount"
        @uploaded="uploaded"
      ></m-upload>
    </view>
  </view>
</template>

<script>
export default {
  name: "m-upload-list",
  props: {
    value: {
      type: Array,
      default: () => {
        return [];
      },
    },
    bgColor: {
      type: String,
      default: "#ffffff",
    },
    size: {
      type: String,
      default: "138rpx",
    },
    count: {
      type: Number,
      default: 10,
    },
  },
  computed: {
    // 上传组件单次可选择图片数量
    uploadCount() {
      return this.count - this.value.length;
    },
  },
  methods: {
    /**
     * 重新选择图片，替换原来图片
     * @param {String} url 图片url
     * @param {Number} index 图片urls下标
     */
    handleToggledPic([url], index) {
      console.log(url, index);
      let urls = this.$m.deepClone(this.value);
      urls.splice(index, 1, url);
      this.$emit("input", urls);
    },
    /**
     * 图片上传完成
     * @param {Array} urls
     */
    uploaded(urls) {
      this.$emit("input", [...this.value, ...urls]);
    },
    /**
     * 删除图片
     * @param {Number} index
     */
    handleDelPic(index) {
      let urls = this.$m.deepClone(this.value);
      urls.splice(index, 1);
      this.$emit("input", urls);
    },
  },
};
</script>

<style lang="scss" scoped>
.m-upload-list-c {
  padding: 20rpx 0;
  display: flex;
  flex-wrap: wrap;

  .item {
    margin: 10rpx;
  }
}
</style>
